import { Injectable } from '@angular/core';
import { ApiService } from '@core/api.service';
import { forkJoin } from 'rxjs';
// import { handoverComponent } from "./handover.component";
// import { handoverRdComponent } from "./handover.readonly.component";
@Injectable({ providedIn: 'root' })

export class HandoverBusiness {

  dutyId = ''; // 当天信息的ID，是除了人员安排外其他表格的请求必要参数
  // handoverCmp: handoverComponent | handoverRdComponent | object;
  handoverCmp: any;
  querySetting;
  addSetting;
  diffSetting = [];

  constructor(
    private apiService: ApiService
  ) { }

  getDutyIdStr() {
    return this.dutyId.toString();
  }

  formatTime(time: any) {
    const theDate: Date = new Date(time);
    const year = theDate.getFullYear();
    let month: any = theDate.getMonth() + 1;
    let _date: any = theDate.getDate();
    if (month < 10) {
      month = '0' + month;
    }
    if (_date < 10) {
      _date = '0' + _date;
    }
    return year + '-' + month + '-' + _date;
  }

  formatDate(date: Date) {
    const year = date.getFullYear();
    let month: any = date.getMonth() + 1;
    let _date: any = date.getDate();
    if (month < 10) {
      month = '0' + month;
    }
    if (_date < 10) {
      _date = '0' + _date;
    }
    return year + '-' + month + '-' + _date;
  }

  getTheMonth() {
    let month: any = new Date(this.handoverCmp.data.today).getMonth() + 1;
    if (month < 10) {
      month = '0' + month;
    }
    return month;
  }

  getToday(num: number = 0, dateValue?: string | Date) {
    let todayDate: Date;
    if (dateValue) {
      // if (typeof dateValue == 'string') {
      //     todayDate = new Date(dateValue);
      // } else if (dateValue instanceof Date) {
      //     todayDate = dateValue;
      // }
      todayDate = new Date(dateValue);
    } else {
      todayDate = new Date();
    }
    todayDate.setDate(todayDate.getDate() + num);
    return this.formatDate(todayDate);
  }

  getTheDate(num: number = 0) {
    const _date = this.handoverCmp.data.today;
    return this.getToday(num, _date);
  }

  /**
   * 对外提供，用于获取外部对象
   * 这里外部指的就是handoverComponent
   * @param obj
   */
  setHandoverCmp(obj: any) {
    this.handoverCmp = obj;
  }


  doRes(res) {
    let _data: any;
    if (typeof (res) == 'object') {
      _data = res.response.data;
    } else {
      _data = JSON.parse(res).response.data;
    }
    if (_data.length == 0) {
      _data = [{}, {}];
    } else if (_data.length == 1) {
      _data.push({});
    }
    return _data;
  }


  getObservables(arr, optType: string) {
    const obs = [];
    arr.forEach(el => {
      const ob = this.getOb(el.name, el.param, optType);
      obs.push(ob);
    });
    return obs;
  }

  /**
   * 根据参数获取observable对象
   */
  getOb = (businessType: string, param: object, optType: string) => this.apiService.handover_dispatcher(businessType, param, optType)

  /**
   * 根据查询配置表获取查询请求的observable对象数组
   */
  getQueryObs() {
    const aqxxArr = this.querySetting.aqxx;
    const scxxArr = this.querySetting.scxx;
    const qtxxArr = this.querySetting.qtxx;
    const aqxxObs = this.getObservables(aqxxArr, 'query');
    const scxxObs = this.getObservables(scxxArr, 'query');
    const qtxxObs = this.getObservables(qtxxArr, 'query');
    return [...aqxxObs, ...scxxObs, ...qtxxObs];
  }

  /**
   * 从查询配置表中获取回调函数的数组
   */
  getQueryCallbacks() {
    const aqxxArr = this.querySetting.aqxx;
    const scxxArr = this.querySetting.scxx;
    const qtxxArr = this.querySetting.qtxx;
    const getFunc = (arr: any[]) => {
      const funcs = [];
      arr.forEach(el => {
        funcs.push(el.func);
      });
      return funcs;
    };
    const aqxxFuncs = getFunc(aqxxArr);
    const scxxFuncs = getFunc(scxxArr);
    const qtxxFuncs = getFunc(qtxxArr);
    return [...aqxxFuncs, ...scxxFuncs, ...qtxxFuncs];

  }

  getSaveCallbacks() {
    const aqxxArr = this.addSetting.aqxx;
    const scxxArr = this.addSetting.scxx;
    const qtxxArr = this.addSetting.qtxx;
    const getFunc = (arr: any[]) => {
      const funcs = [];
      arr.forEach(el => {
        funcs.push(el.func);
      });
      return funcs;
    };
    const aqxxFuncs = getFunc(aqxxArr);
    const scxxFuncs = getFunc(scxxArr);
    const qtxxFuncs = getFunc(qtxxArr);
    return [...aqxxFuncs, ...scxxFuncs, ...qtxxFuncs];
  }

  consoleLog(str: string) {
    console.log(str);
  }

  /**
   * 设置querySetting的值，
   * querySetting是查询请求的配置表
   * 包括请求名，参数和回调
   */
  setQuerySetting() {
    this.querySetting = {
      aqxx: [// 安全信息
        // 高铁
        {
          name: 'aqxx_gpt',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            'HIGH': '1',
          },
          func: (res) => {
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.aqxx.gt = this.cleanUp(_data);
          }
        },
        // 普铁
        {
          name: 'aqxx_gpt',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            'HIGH': '2',
          },
          func: (res) => {
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.aqxx.pt = this.cleanUp(_data);
          }
        },
        // 其他
        {
          name: 'aqxx_qt',
          param: {
            DUTY_ID: this.getDutyIdStr(),
          },
          func: (res) => {
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.aqxx.qtxx = this.cleanUp(_data);
          }
        },
        // 日安全信息分析追踪
        {
          name: 'aqxx_rzz',
          param: {
            DUTY_ID: this.getDutyIdStr(),
          },
          func: (res) => {
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.aqxx.raqxxfxzz = this.cleanUp(_data);
          }
        },
        // 日安全风险提示
        {
          name: 'aqxx_ts',
          param: {
            DUTY_ID: this.getDutyIdStr(),
          },
          func: (res) => {
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.aqxx.raqfxts = this.cleanUp(_data);
          }
        }],
      scxx: [
        // 段生产重点追踪信息反馈
        {
          name: 'scxx_dfk',
          param: {
            DUTY_ID: this.getDutyIdStr(),
          },
          func: (res) => {
            if (!res) {
              this.consoleLog('查无结果：段生产重点追踪信息反馈 scxx_dfk');
              return;
            }
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.scxx.dfk = this.cleanUp(_data);
          }
        },
        // 总公司、集团公司日安全分析重点追踪信息
        {
          name: 'scxx_zgs_dzz',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            TYPE: '0'
          },
          func: (res) => {
            if (!res) {
              this.consoleLog('查无结果：总公司、集团公司日安全分析重点追踪信息 scxx_zgs_dzz');
              return;
            }
            let _data: any;
            if (typeof (res) == 'object') {
              _data = res.response.data;
            } else {
              _data = JSON.parse(res).response.data;
            }
            if (_data.length == 0) {
              _data = [{}, {}];
            } else if (_data.length == 1) {
              _data.push({});
            }
            this.forceEnter(_data);
            _data.forEach(row => {
              if (row.VC_FINISH == '1') {
                row._vcFinished = true;
              }
            });
            for (const item of _data) {
              if (item.TRACK_REQ) { // 页面保存后向下跳动，暂时用清理换行解决
                item.NEWINF_REQ = this.formatData(item.INF_REQ);
                item.NEWREFORM_INFO = this.formatData(item.REFORM_INFO);
              }
            }
            this.handoverCmp.data.scxx.zgszz = this.cleanUp(_data);
          }
        },
        // 段日安全分析重点追踪信息反馈
        {
          name: 'scxx_zgs_dzz',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            TYPE: '1',
          },
          func: (res) => {
            if (!res) {
              this.consoleLog('查无结果：段日安全分析重点追踪信息反馈 scxx_zgs_dzz');
              return;
            }
            let _data: any;
            if (typeof (res) == 'object') {
              _data = res.response.data;
            } else {
              _data = JSON.parse(res).response.data;
            }
            if (_data.length == 0) {
              _data = [{}, {}];
            } else if (_data.length == 1) {
              _data.push({});
            }
            this.forceEnter(_data);
            this.handoverCmp.data.scxx.dzz = this.cleanUp(_data);
          }
        },
        // 昨日施工计划:
        {
          name: 'scxx_tcjh_sgph',
          param: {
            'PLAN_DATE': this.getTheDate(),
            'PEIHE': '1',
          },
          func: (res) => {
            if (!res) {
              this.consoleLog('查无结果：昨日施工计划 scxx_tcjh_sgph');
              return;
            }
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.scxx.tcjhqk.zrsgjh = this.cleanUp(_data);
          }
        },
        // 今日施工计划:
        {
          name: 'scxx_tcjh_sgph',
          param: {
            'PLAN_DATE': this.getTheDate(1),
            'PEIHE': '1',
          },
          func: (res) => {
            if (!res) {
              this.consoleLog('查无结果：今日施工计划 scxx_tcjh_sgph');
              return;
            }
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.scxx.tcjhqk.jrsgjh = this.cleanUp(_data);
          }
        },
        // 昨日施工配合计划
        {
          name: 'scxx_tcjh_sgph',
          param: {
            'PLAN_DATE': this.getTheDate(),
            'PEIHE': '2',
          },
          func: (res) => {
            if (!res) {
              this.consoleLog('查无结果：昨日施工配合计划 scxx_tcjh_sgph');
              return;
            }
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.scxx.tcjhqk.zrsgphjh = this.cleanUp(_data);
          }
        },
        // 今日施工配合计划：
        {
          name: 'scxx_tcjh_sgph',
          param: {
            'PLAN_DATE': this.getTheDate(1),
            'PEIHE': '2',
          },
          func: (res) => {
            if (!res) {
              this.consoleLog('查无结果：今日施工配合计划 scxx_tcjh_sgph');
              return;
            }
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.scxx.tcjhqk.jrsgphjh = this.cleanUp(_data);
          }
        },
        // 维修计划(昨日)
        {
          name: 'scxx_tcjh_wxjh',
          param: {
            'REPAIR_DATE': this.getTheDate(),
          },
          func: (res) => {
            this.handoverCmp.data.scxx.tcjhqk.zrwxjh = {
              I: {
                gt: [{}],
                pt: [{}],
              },
              II: {
                gt: [{}],
                pt: [{}],
              },
            };
            if (!res) {
              this.consoleLog('查无结果：维修计划 scxx_tcjh_wxjh');
              return;
            }
            let _data: any;
            if (typeof (res) == 'object') {
              _data = res.response.data;
            } else {
              _data = JSON.parse(res).response.data;
            }
            _data = this.cleanUp(_data);
            if (_data.length == 0) {
              _data = [{}, {}, {}, {}];
            } else {
              // _data.forEach(el => {
              //     el._REPAIR_DATE = el.REPAIR_DATE;
              //     el.REPAIR_DATE = this.formatTime(el.REPAIR_DATE);
              // });
              for (let i = 0; i < _data.length; i++) {
                const el = _data[i];
                if (el && el.REPAIR_LEVEL) {// Ⅰ
                  if (el.REPAIR_LEVEL.includes('II') ||
                    el.REPAIR_LEVEL.includes('ⅠⅠ') ||
                    el.REPAIR_LEVEL.includes('Ⅱ')) {
                    if (el.LINE == '高铁') {
                      this.handoverCmp.data.scxx.tcjhqk.zrwxjh.II.gt = [el];
                    } else if (el.LINE == '普铁') {
                      this.handoverCmp.data.scxx.tcjhqk.zrwxjh.II.pt = [el];
                    }
                  } else if (el.REPAIR_LEVEL.includes('I') || el.REPAIR_LEVEL.includes('Ⅰ')) {
                    if (el.LINE == '高铁') {
                      this.handoverCmp.data.scxx.tcjhqk.zrwxjh.I.gt = [el];
                    } else if (el.LINE == '普铁') {
                      this.handoverCmp.data.scxx.tcjhqk.zrwxjh.I.pt = [el];
                    }
                  }
                }

              }
            }

            // this.handoverCmp.data.scxx.tcjhqk.zrwxjh = _data;
            // this.handoverCmp.data.scxx.tcjhqk.wxjh.push(_data);
          }
        },
        // 维修计划(今日)
        {
          name: 'scxx_tcjh_wxjh',
          param: {
            'REPAIR_DATE': this.getTheDate(1),
          },
          func: (res) => {
            this.handoverCmp.data.scxx.tcjhqk.jrwxjh = {
              I: {
                gt: [{}],
                pt: [{}],
              },
              II: {
                gt: [{}],
                pt: [{}],
              },
            };
            if (!res) {
              this.consoleLog('查无结果：维修计划 scxx_tcjh_wxjh');
              return;
            }
            let _data: any;
            if (typeof (res) == 'object') {
              _data = res.response.data;
            } else {
              _data = JSON.parse(res).response.data;
            }
            _data = this.cleanUp(_data);
            if (_data.length == 0) {
              _data = [];
            } else {
              for (let i = 0; i < _data.length; i++) {
                const el = _data[i];
                if (el && el.REPAIR_LEVEL) {
                  if (el.REPAIR_LEVEL.includes('II') ||
                    el.REPAIR_LEVEL.includes('ⅠⅠ') ||
                    el.REPAIR_LEVEL.includes('Ⅱ')) {
                    if (el.LINE == '高铁') {
                      this.handoverCmp.data.scxx.tcjhqk.jrwxjh.II.gt = [el];
                    } else if (el.LINE == '普铁') {
                      this.handoverCmp.data.scxx.tcjhqk.jrwxjh.II.pt = [el];
                    }
                  } else if (el.REPAIR_LEVEL.includes('I') || el.REPAIR_LEVEL.includes('Ⅰ')) {
                    if (el.LINE == '高铁') {
                      this.handoverCmp.data.scxx.tcjhqk.jrwxjh.I.gt = [el];
                    } else if (el.LINE == '普铁') {
                      this.handoverCmp.data.scxx.tcjhqk.jrwxjh.I.pt = [el];
                    }
                  }
                }
              }
            }
            // this.handoverCmp.data.scxx.tcjhqk.wxjh = this.handoverCmp.data.scxx.tcjhqk.wxjh.concat(_data);
            // this.handoverCmp.data.scxx.tcjhqk.jrwxjh.push(_data);
          }
        },
        // 紧急修计划
        {
          name: 'scxx_tcjh_jjxjh',
          param: {
            DUTY_ID: this.getDutyIdStr(),
          },
          func: (res) => {
            if (!res) {
              this.consoleLog('查无结果：紧急修计划 scxx_tcjh_jjxjh');
              return;
            }
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.scxx.tcjhqk.jjxjh = this.cleanUp(_data);
          }
        },

        // 车载数据换装及升级情况
        {
          name: 'scxx_czsj',
          param: {
            DUTY_ID: this.getDutyIdStr(),
          },
          func: (res) => {
            if (!res) {
              this.consoleLog('查无结果：车载数据换装及升级情况 scxx_czsj');
              return;
            }
            let _data: any;
            if (typeof (res) == 'object') {
              _data = res.response.data;
            } else {
              _data = JSON.parse(res).response.data;
            }
            this.forceEnter(_data);
            if (_data.length == 0) {
              _data = [{}, {}];
            } else {
              if (_data.length == 1) {
                _data.push({});
              }
              _data.forEach(el => {
                if (el.FINISH) {
                  el.FINISH = el.FINISH.toString();
                }
                if (el.TOTAL) {
                  el.TOTAL = el.TOTAL.toString();
                }
                if (el.UNFINISH) {
                  el.UNFINISH = el.UNFINISH.toString();
                }
              });
            }
            this.handoverCmp.data.scxx.czsj = this.cleanUp(_data);
          }
        },
        // 分路不良统计分析
        {
          name: 'scxx_flbltj',
          param: {
            ANALY_DATE: this.getTheDate(),
            // DUTY_ID: this.getDutyIdStr(),
          },
          func: (res) => {
            if (!res) {
              this.consoleLog('查无结果：分路不良统计分析 scxx_flbltj');
              return;
            }
            let _data: any;
            if (typeof (res) == 'object') {
              _data = res.response.data;
            } else {
              _data = JSON.parse(res).response.data;
            }
            this.forceEnter(_data);
            if (_data.length == 0) {
              _data = [{}, {}];
            } else {
              if (_data.length == 1) {
                _data.push({});
              }
              _data.forEach(el => {
                // if (el.ANALY_DATE) {
                //   el._ANALY_DATE = el.ANALY_DATE;
                //   el.ANALY_DATE = this.formatTime(el._ANALY_DATE);
                // }
                if (el.CHANGE) {
                  el.CHANGE = el.CHANGE.toString();
                }
                if (el.DAY) {
                  el.DAY = el.DAY.toString();
                }
                if (el.YESTERDAY) {
                  el.YESTERDAY = el.YESTERDAY.toString();
                }
              });
            }
            this.handoverCmp.data.scxx.flbltj = this.cleanUp(_data);
          }
        },

        // 领导、干部行踪：
        {
          name: 'scxx_ldxz',
          param: {
            DUTY_ID: this.getDutyIdStr(),
          },
          func: (res) => {
            if (!res) {
              this.consoleLog('查无结果：领导、干部行踪 scxx_ldxz');
              return;
            }
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.scxx.ldxz = this.cleanUp(_data);
          }
        },

        // 今日追踪配合：(实际是明日)
        {
          name: 'ryap',
          param: {
            'DUTY_DATE': this.getTheDate(1)
          },
          func: (res) => {
            let _data: any;
            if (typeof (res) == 'object') {
              _data = res.response.data;
            } else {
              _data = JSON.parse(res).response.data;
            }
            this.forceEnter(_data);
            _data = this.cleanUp(_data);
            if (_data[0].TIANCHUAN_INFO == 'null') {
              _data[0].TIANCHUAN_INFO = '';
            }
            this.handoverCmp.data.scxx.jrzzph[0].TIANCHUAN_INFO = _data[0].TIANCHUAN_INFO;
            this.handoverCmp.data.scxx.jrzzph[0].TC_INFO = _data[0].TC_INFO;
            // this.handoverCmp.data.scxx.zrzzph[0].TIANCHUAN_INFO = _data[0].TIANCHUAN_INFO;
          }
        },
      ],
      qtxx: [
        // 安全预警书统计情况
        {
          name: 'qtxx_aqyjs',
          param: {
            DUTY_ID: this.getDutyIdStr(),
          },
          func: (res) => {
            if (!res) {
              this.consoleLog('查无结果：安全预警书统计情况 qtxx_aqyjs');
              return;
            }
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.qtxx.aqyjstj = this.cleanUp(_data);
          }
        },

        // 安全风险通知书统计
        {
          name: 'qtxx_fxtzs',
          param: {
            DUTY_ID: this.getDutyIdStr(),
          },
          func: (res) => {
            if (!res) {
              this.consoleLog('查无结果：安全风险通知书统计 qtxx_fxtzs');
              return;
            }
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.qtxx.aqfxtzstj = this.cleanUp(_data);
          }
        },
        // 交班重点工作要求
        {
          name: 'qtxx_jbyq',
          param: {
            DUTY_ID: this.getDutyIdStr(),
          },
          func: (res) => {
            if (!res) {
              this.consoleLog('查无结果：交班重点工作要求 qtxx_jbyq');
              return;
            }
            const _data = this.doRes(res);
            this.forceEnter(_data);
            this.handoverCmp.data.qtxx.jbyq = this.cleanUp(_data);
          }
        }
      ]

    };
  }

  formatData(data) {
    return JSON.stringify(data).replace(/\"/g, '').replace(/↵/g, '').replace(/\\r\n/g, '').replace(/\\n/g, '');
  }

  setAddSetting() {
    const getFunc = (title) => {
      const commonFunc = (res) => {
        let _data;
        const _title = title;
        if (typeof res == 'string') {
          _data = JSON.parse(res);
        } else {
          _data = res;
        }
        if (_data.type == 'success') {
          this.handoverCmp.message.create('success', _title + '保存成功');
        } else {
          this.handoverCmp.message.create('error', _title + '保存失败');
        }
      };
      return commonFunc;
    };

    this.addSetting = {
      head: {// 专用于编辑
        name: 'ryap',
        param: {
          DUTY_DATE: '',
          DIS_ARRANGE: '',
          DEP_ARRANGE: '',
          DRIVER: '',
          ARRANGE: '',
          ID: '',
        },
        func: getFunc(' 人员安排 ')
      },
      aqxx: {
        gt: {
          name: 'aqxx_gpt',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            ORG: '',
            STATION: '',
            RECORD: '',
            EFFECT: '',
            DESCR: '',
            HANDLE: '',
            TRACK: '',
            HIGH: '1',
          },
          func: getFunc(' 高铁信息 ')
        },
        pt: {
          name: 'aqxx_gpt',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            ORG: '',
            STATION: '',
            RECORD: '',
            EFFECT: '',
            DESCR: '',
            HANDLE: '',
            TRACK: '',
            HIGH: '2',
          },
          func: getFunc(' 普铁信息 ')
        },
        qtxx: {
          name: 'aqxx_qt',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            INFOR: '',
          },
          func: getFunc(' 其他信息 ')
        },
        raqxxfxzz: {
          name: 'aqxx_rzz',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            INFOR: '',
          },
          func: getFunc(' 日安全信息分析追踪 ')
        },
        raqfxts: {
          name: 'aqxx_ts',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            INFOR: '',
          },
          func: getFunc(' 日安全风险提示 ')
        },
      },
      scxx: {
        dfk: {
          name: 'scxx_dfk',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            ORG: '',
            INF_REQ: '',
            INFOR: '',
            REFORM: '',
            HANDLE: '',
          },
          func: getFunc(' 段生产重点追踪信息反馈 ')
        },
        zgszz: {
          name: 'scxx_zgs_dzz',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            PROBLEM_TIME: '',
            SOURCE: '',
            INF_REQ: '',
            TRACK_REQ: '',
            CHARGE: '',
            REFORM_INFO: '',
            FINISHDATE: '',
            HANDLE: '',
            vcFinished: '',
            TYPE: '0',
            INFO: this.handoverCmp.data.scxx.safeinfo
          },
          func: getFunc(' 总公司、集团公司日安全分析重点追踪信息 ')
        },
        dzz: {
          name: 'scxx_zgs_dzz',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            PROBLEM_TIME: '',
            SOURCE: '',
            INF_REQ: '',
            TRACK_REQ: '',
            CHARGE: '',
            REFORM_INFO: '',
            FINISHDATE: '',
            HANDLE: '',
            vcFinished: '',
            TYPE: '1',
            INFO: this.handoverCmp.data.scxx.trackinfo
          },
          func: getFunc(' 段日安全分析重点追踪信息反馈 ')
        },
        tcjhqk: {
          zrsgjh: {
            name: 'scxx_tcjh_sgph',
            param: {
              DUTY_ID: this.getDutyIdStr(),
              PLAN_NUM: '',
              PLAN_LEVEL: '',
              ADDR: '',
              PLAN_TIME: '',
              CONTENT: '',
              PERSON: '',
              STATUS: '',
              PROBLEM: '',
              PLAN_DATE: this.getTheDate(),
              PEIHE: '1'
            },
            func: getFunc(' 昨日施工计划 ')
          },
          jrsgjh: {
            name: 'scxx_tcjh_sgph',
            param: {
              DUTY_ID: this.getDutyIdStr(),
              PLAN_NUM: '',
              PLAN_LEVEL: '',
              ADDR: '',
              PLAN_TIME: '',
              CONTENT: '',
              PERSON: '',
              STATUS: '',
              PROBLEM: '',
              PLAN_DATE: this.getTheDate(1),
              PEIHE: '1'
            },
            func: getFunc(' 今日施工计划 ')
          },
          zrsgphjh: {
            name: 'scxx_tcjh_sgph',
            param: {
              DUTY_ID: this.getDutyIdStr(),
              PLAN_NUM: '',
              PLAN_LEVEL: '',
              ADDR: '',
              PLAN_TIME: '',
              CONTENT: '',
              PERSON: '',
              STATUS: '',
              PROBLEM: '',
              PLAN_DATE: this.getTheDate(),
              PEIHE: '2',
              INFO: this.handoverCmp.data.scxx.copuinfo
            },
            func: getFunc(' 昨日施工配合计划 ')
          },
          jrsgphjh: {
            name: 'scxx_tcjh_sgph',
            param: {
              DUTY_ID: this.getDutyIdStr(),
              PLAN_NUM: '',
              PLAN_LEVEL: '',
              ADDR: '',
              PLAN_TIME: '',
              CONTENT: '',
              PERSON: '',
              STATUS: '',
              PROBLEM: '',
              PLAN_DATE: this.getTheDate(1),
              PEIHE: '2',
              INFO: this.handoverCmp.data.scxx.dayinfo
            },
            func: getFunc(' 今日施工配合计划 ')
          },
          zrwxjh: {
            I: {
              gt: {
                name: 'scxx_tcjh_wxjh',
                param: {
                  REPAIR_DATE: this.getTheDate(),
                  REPAIR_LEVEL: 'Ⅰ',
                  LINE: '高铁',
                  NUM: '',
                  CONTENT: '',
                  FINISH_NUM: '',
                  PERSON: '',
                  STATUS: '',
                  REMARK: '',
                  PLAN_DETAIL: '',
                },
                func: getFunc(' 维修计划 ')
              },
              pt: {
                name: 'scxx_tcjh_wxjh',
                param: {
                  REPAIR_DATE: this.getTheDate(),
                  REPAIR_LEVEL: 'Ⅰ',
                  LINE: '普铁',
                  NUM: '',
                  CONTENT: '',
                  FINISH_NUM: '',
                  PERSON: '',
                  STATUS: '',
                  REMARK: '',
                  PLAN_DETAIL: '',
                },
                func: getFunc(' 维修计划 ')
              }
            },
            II: {
              gt: {
                name: 'scxx_tcjh_wxjh',
                param: {
                  REPAIR_DATE: this.getTheDate(),
                  REPAIR_LEVEL: 'Ⅱ',
                  LINE: '高铁',
                  NUM: '',
                  CONTENT: '',
                  FINISH_NUM: '',
                  PERSON: '',
                  STATUS: '',
                  REMARK: '',
                  PLAN_DETAIL: '',
                },
                func: getFunc(' 维修计划 ')
              },
              pt: {
                name: 'scxx_tcjh_wxjh',
                param: {
                  REPAIR_DATE: this.getTheDate(),
                  REPAIR_LEVEL: 'Ⅱ',
                  LINE: '普铁',
                  NUM: '',
                  CONTENT: '',
                  FINISH_NUM: '',
                  PERSON: '',
                  STATUS: '',
                  REMARK: '',
                  PLAN_DETAIL: '',
                },
                func: getFunc(' 维修计划 ')
              }
            }
          },
          jrwxjh: {
            I: {
              gt: {
                name: 'scxx_tcjh_wxjh',
                param: {
                  REPAIR_DATE: this.getTheDate(1),
                  REPAIR_LEVEL: 'Ⅰ',
                  LINE: '高铁',
                  NUM: '',
                  CONTENT: '',
                  FINISH_NUM: '',
                  PERSON: '',
                  STATUS: '',
                  REMARK: '',
                  PLAN_DETAIL: '',
                },
                func: getFunc(' 维修计划 ')
              },
              pt: {
                name: 'scxx_tcjh_wxjh',
                param: {
                  REPAIR_DATE: this.getTheDate(1),
                  REPAIR_LEVEL: 'Ⅰ',
                  LINE: '普铁',
                  NUM: '',
                  CONTENT: '',
                  FINISH_NUM: '',
                  PERSON: '',
                  STATUS: '',
                  REMARK: '',
                  PLAN_DETAIL: '',
                },
                func: getFunc(' 维修计划 ')
              }
            },
            II: {
              gt: {
                name: 'scxx_tcjh_wxjh',
                param: {
                  REPAIR_DATE: this.getTheDate(1),
                  REPAIR_LEVEL: 'Ⅱ',
                  LINE: '高铁',
                  NUM: '',
                  CONTENT: '',
                  FINISH_NUM: '',
                  PERSON: '',
                  STATUS: '',
                  REMARK: '',
                  PLAN_DETAIL: '',
                },
                func: getFunc(' 维修计划 ')
              },
              pt: {
                name: 'scxx_tcjh_wxjh',
                param: {
                  REPAIR_DATE: this.getTheDate(1),
                  REPAIR_LEVEL: 'Ⅱ',
                  LINE: '普铁',
                  NUM: '',
                  CONTENT: '',
                  FINISH_NUM: '',
                  PERSON: '',
                  STATUS: '',
                  REMARK: '',
                  PLAN_DETAIL: '',
                },
                func: getFunc(' 维修计划 ')
              }
            }
          },
          jjxjh: {
            name: 'scxx_tcjh_jjxjh',
            param: {
              DUTY_ID: this.getDutyIdStr(),
              ORG: '',
              NUM: '',
              CONTENT: '',
              FOLLOW: '',
            },
            func: getFunc(' 紧急修计划 ')
          },
        },
        czsj: {
          name: 'scxx_czsj',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            VERSON: '',
            CONTENT: '',
            TOTAL: '',
            FINISH: '',
            UNFINISH: '',
            REMARK: '',
          },
          func: getFunc(' 车载数据换装及升级情况 ')
        },
        flbltj: {
          name: 'scxx_flbltj',
          param: {
            ANALY_DATE: '',
            DAY: '',
            CHANGE: '',
            YESTERDAY: '',
            CONTENT: '',
          },
          func: getFunc(' 分路不良统计分析 ')
        },
        ldxz: {
          name: 'scxx_ldxz',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            NAME: '',
            JOB: '',
            ADDR: '',
            CONTENT: '',
          },
          func: getFunc(' 领导、干部行踪 ')
        },
        zzph: {
          name: 'scxx_zzph',
          param: {
            DUTY_DATE: this.getTheDate(),
            IMP_TRACK_INFO: '',
            IMP_TRACK_INFO_DUAN: '',
            TIANCHUAN_INFO: '',
            DIANWAI: '',
            TC_INFO: '',
            PROD_INFO: '',
            EMER_INFO: '',
          },
          func: getFunc('')
        },
        jrzzph: {
          name: 'scxx_zzph',
          param: {
            DUTY_DATE: this.getTheDate(1),
            TIANCHUAN_INFO: '',
            TC_INFO: ''
          },
          func: getFunc('')
        }
      },
      qtxx: {
        aqyjstj: {
          name: 'qtxx_aqyjs',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            TYPE: '',
            NO: '',
            PERSON: '',
            APPROVE: '',
            ORG: '',
            WARNING: '',
            REQUIRE: '',
          },
          func: getFunc(' 安全预警书统计情况 ')
        },
        aqfxtzstj: {
          name: 'qtxx_fxtzs',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            TYPE: '',
            PRO: '',
            PERSON: '',
            RISK: '',
            ORG: '',
            CONTENT: '',
            SUPERVISION: '',
            REQUIRE: '',
          },
          func: getFunc(' 安全风险通知书统计 ')
        },
        jbyq: {
          name: 'qtxx_jbyq',
          param: {
            DUTY_ID: this.getDutyIdStr(),
            REQUIRE: '',
            FINISH: '',
            ORG: '',
          },
          func: getFunc(' 交班重点工作要求 ')
        }
      }
    };
  }


  /**
   * 使用forkJoin方式发送请求
   * forkJoin:在查询请求全部结束后回调
   */
  getAllInfo_forkJoin() {
    const obs = this.getQueryObs();
    const funcs = this.getQueryCallbacks();
    forkJoin(...obs).subscribe(resArr => {
      for (let i = 0; i < resArr.length; i++) {
        const res = resArr[i];
        funcs[i].call(this, res);
      }
      this.handoverCmp.backupData();
      this.handoverCmp.user.loading = false;
    });
  }

  forceEnter(rows) {
    rows.forEach(row => {
      const keys = Object.keys(row);
      keys.forEach(key => {
        if (typeof (row[key]) == 'string' && row[key].length >= 50) {
          row[key] += '\n';
        }
      });
    });
  }

  saveAllInfo_forkJoin() {
    this.handoverCmp.user.loading = true;
    const dif = this.handoverCmp.getDataDiff();
    // this.setAddSetting();//test
    if (!dif) {
      this.handoverCmp.user.loading = false;
      this.handoverCmp.user.saveAble = true;
      return;
    }
    this.diffSetting = [];
    this.loopDif2(dif, this.addSetting);
    const obs = [], funcs = [];
    this.diffSetting.forEach(el => {
      obs.push(el.ob);
      funcs.push(el.func);
    });
    if (obs.length) {
      // 测试用
      // this.handoverCmp.backupData();
      // let dif = this.handoverCmp.getDataDiff();
      forkJoin(...obs).subscribe(resArr => {
        for (let i = 0; i < resArr.length; i++) {
          const res = resArr[i];
          funcs[i].call(this, res);
        }
        this.handoverCmp.backupData();
        this.handoverCmp.user.loading = false;
        this.handoverCmp.user.saveAble = true;
        this.getAllInfo();
      });
    }
  }

  /**
   * 查询总方法
   */
  getAllInfo() {
    // this.setAddSetting();//测试用
    this.handoverCmp.user.loading = true;
    const getTheOthersInfo = function () {
      if (!this.dutyId) {
        return;
      }
      this.setQuerySetting();
      this.setAddSetting();
      this.getAllInfo_forkJoin();
    };
    this.getRyap(getTheOthersInfo); // 获取人员安排信息及当天安排的ID
    if (this.handoverCmp.editable) {
      this.getCj();
    }
  }

  getInfo(infoName: string, param: object, func: Function) {
    this.apiService.handover_dispatcher(infoName, param, 'query').subscribe(res => {
      func.call(this, res);
    });
  }

  saveInfo(infoName: string, param: object, func: Function) {
    this.apiService.handover_dispatcher(infoName, param, 'save').subscribe(res => {
      func.call(this, res);
    });
  }

  addInfo(infoName: string, param: object, func: Function) {
    this.apiService.handover_dispatcher(infoName, param, 'add').subscribe(res => {
      func.call(this, res);
    });
  }

  delInfo(infoName: string, param: object, func: Function) {
    this.apiService.handover_dispatcher(infoName, param, 'del').subscribe(res => {
      func.call(this, res);
    });
  }

  callMedthodsByDif() {
    const dif = this.handoverCmp.getDataDiff();
    if (dif) {
      this.loopDif(dif, this.addSetting);
    }

  }

  parsePropDate(param) {
    for (const pkey in param) {
      if (param.hasOwnProperty(pkey)) {
        const pEl = param[pkey];
        if (pEl instanceof Date) {
          param[pkey] = this.formatDate(pEl);
        }
      }
    }
  }

  loopDif(dif, addSettingObj) {
    for (const key in dif) {
      if (dif.hasOwnProperty(key) && key != 'user') {
        const difItem = dif[key];
        if (difItem.adds) {// 叶子节点
          const _name = addSettingObj[key].name;
          const _param = JSON.parse(JSON.stringify(addSettingObj[key].param));
          const _func = addSettingObj[key].func;
          if (difItem.adds.length > 0) {
            const el = difItem.adds;
            el.forEach(_item => {
              const param = Object.assign(_param, _item);
              this.parsePropDate(param); 
              this.addInfo(_name, param, _func);
            });
          }
          if (difItem.edits.length > 0) {
            const el = difItem.edits;
            el.forEach(_item => {
              const param = Object.assign(_param, _item);
              this.parsePropDate(param); 
              this.saveInfo(_name, param, _func);
            });
          }
          if (difItem.dels.length > 0) {
            const el = difItem.dels;
            el.forEach(_item => {
              const param = { ID: _item.ID };
              // let param = Object.assign(_param, _item);
              this.delInfo(_name, param, _func);
            });
          }
        } else {
          if (addSettingObj[key]) {
            this.loopDif(difItem, addSettingObj[key]);
          }
        }

      }
    }
  }

  loopDif2(dif, addSettingObj) {
    if (!dif && !addSettingObj) {
      return;
    }
    for (const key in dif) {
      if (dif.hasOwnProperty(key) && key != 'user') {
        const difItem = dif[key];
        if (difItem.adds) {// 叶子节点
          const _name = addSettingObj[key].name;
          const _param = JSON.parse(JSON.stringify(addSettingObj[key].param));
          const _func = addSettingObj[key].func;
          if (difItem.adds.length > 0) {
            const el = difItem.adds;
            el.forEach(_item => {
              const param = Object.assign(_param, _item);
              this.parsePropDate(param);
              // this.addInfo(_name, param, _func);
              const ob = this.getOb(_name, param, 'add');
              this.diffSetting.push({
                ob,
                func: _func
              });
            });
          }
          if (difItem.edits.length > 0) {
            const el = difItem.edits;
            el.forEach(_item => {
              const param = Object.assign(_param, _item);
              this.parsePropDate(param);
              // this.saveInfo(_name, param, _func);
              const ob = this.getOb(_name, param, 'save');
              this.diffSetting.push({
                ob,
                func: _func
              });
            });
          }
          if (difItem.dels.length > 0) {
            const el = difItem.dels;
            el.forEach(_item => {
              const param = { ID: _item.ID };
              // let param = Object.assign(_param, _item);
              // this.delInfo(_name, param, _func);
              const ob = this.getOb(_name, param, 'del');
              this.diffSetting.push({
                ob,
                func: _func
              });
            });
          }
        } else {
          if (addSettingObj[key]) {
            this.loopDif2(difItem, addSettingObj[key]);
          }
        }

      }
    }
  }

  saveAllInfo() {
    this.callMedthodsByDif();
    // this.getAllInfo();
  }

  getRyap(func: Function) {
    this.getInfo('ryap', {
      'DUTY_DATE': this.getTheDate()
    }, function (res) {
      let _data: any;
      if (typeof (res) == 'object') {
        _data = res.response.data;
      } else {
        _data = JSON.parse(res).response.data;
      }
      if (_data.length == 0) {
        _data = [];
      } else {
        // _data.forEach(el => {
        //     el._DUTY_DATE = el.DUTY_DATE;
        //     el.DUTY_DATE = this.formatTime(el.DUTY_DATE);
        // });
        this.dutyId = _data[0].ID;
        // this.dutyId = _data[_data.length - 1].ID
      }
      this.handoverCmp.data.head = _data;
      if (_data[0].IMP_TRACK_INFO == 'null') {
        _data[0].IMP_TRACK_INFO = '';
      }
      if (_data[0].IMP_TRACK_INFO_DUAN == 'null') {
        _data[0].IMP_TRACK_INFO_DUAN = '';
      }
      if (_data[0].TIANCHUAN_INFO == 'null') {
        _data[0].TIANCHUAN_INFO = '';
      }
      this.handoverCmp.data.scxx.zzph[0].IMP_TRACK_INFO = _data[0].IMP_TRACK_INFO;
      this.handoverCmp.data.scxx.zzph[0].IMP_TRACK_INFO_DUAN = _data[0].IMP_TRACK_INFO_DUAN;
      this.handoverCmp.data.scxx.zzph[0].TIANCHUAN_INFO = _data[0].TIANCHUAN_INFO;
      this.handoverCmp.data.scxx.zzph[0].DIANWAI = _data[0].DIANWAI;
      this.handoverCmp.data.scxx.zzph[0].TC_INFO = _data[0].TC_INFO;
      this.handoverCmp.data.scxx.zzph[0].PROD_INFO = _data[0].PROD_INFO;
      this.handoverCmp.data.scxx.zzph[0].EMER_INFO = _data[0].EMER_INFO;
      func.call(this, null);
    });
  }

  /**
   * 查询车站和车间
   */
  getCj() {
    this.getInfo('get_cj', {
      // 'DUTY_DATE': this.getTheDate()
    }, function (res) {
      const _data = res.response.data;
      // if (_data.length == 0) {

      // } else {

      // }
      this.handoverCmp.user.cj = _data;
      this.handoverCmp.user.cj_filter = _data;
    });
  }

  /**
   * 根据车间ID查询车站
   */
  getCz(id: string = '') {
    this.getInfo('get_cz', {
      // 'orgid': 'KMBUR_KMNSEG_ORG_8',
      'orgid': id,
    }, function (res) {
      const _data = res.response.data;
      // if (_data.length == 0) {

      // } else {

      // }
      this.handoverCmp.user.cz = _data;
    });
  }

  getTcjhb(id: string) {
    this.handoverCmp.tcjhb.data = [];
    this.handoverCmp.tcjhb.backupData = [];
    this.handoverCmp.tcjhb.repairid = id;
    this.handoverCmp.tcjhb.loading = true;
    this.getInfo('scxx_tcjh_wxjh_tcjhb', {
      'REPAIRID': id,
    }, function (res) {
      const _data = res.response.data;
      // if (_data.length == 0) {

      // } else {

      // }
      this.handoverCmp.tcjhb.data = _data;
      this.handoverCmp.tcjhb.itemsRepairDayTotal = res.response.totalCount;
      this.handoverCmp.tcjhb.backupData = JSON.parse(JSON.stringify(_data));
      this.handoverCmp.tcjhb.loading = false;
    });
  }

  loopTcjhbDif() {
    const difItem = this.handoverCmp.getArraysDiff(this.handoverCmp.tcjhb.data, this.handoverCmp.tcjhb.backupData);
    if (!difItem) {
      return;
    }
    const _param = {
      REPAIRID: this.handoverCmp.tcjhb.repairid,
      PLANCODE: '',
      STATION: '',
      XINGBIE: '',
      PROJECT: '',
      TC_TYPE: '',
      CONTENT: '',
      TIME: '',
      FINISHDATE: '',
      CHARGE: '',
      UNIT: '',
      WORK_UNIT: '',
      NOTE: '',
    };
    const _name = 'scxx_tcjh_wxjh_tcjhb';
    const tcjhbObs = [];
    const itemNames = [];
    const optType = [];
    if (difItem.adds.length > 0) {
      const el = difItem.adds;
      el.forEach(_item => {
        const param = Object.assign(_param, _item);
        this.parsePropDate(param);
        const ob = this.getOb(_name, param, 'add');
        tcjhbObs.push(ob);
        itemNames.push();
        optType.push('增加');
      });
    }
    if (difItem.edits.length > 0) {
      const el = difItem.edits;
      el.forEach(_item => {
        const param = Object.assign(_param, _item);
        this.parsePropDate(param);
        const ob = this.getOb(_name, param, 'save');
        tcjhbObs.push(ob);
        itemNames.push(param.PLANCODE);
        optType.push('修改');
      });
    }
    if (difItem.dels.length > 0) {
      const el = difItem.dels;
      el.forEach(_item => {
        const param = { ID: _item.ID };
        const ob = this.getOb(_name, param, 'del');
        tcjhbObs.push(ob);
        itemNames.push(_item.PLANCODE || _item.ID);
        optType.push('删除');
      });
    }
    return [tcjhbObs, itemNames, optType];
  }

  saveTcjhb() {
    const resArr = this.loopTcjhbDif();
    const obs = resArr[0];
    const itemNames = resArr[1];
    const optType = resArr[2];
    forkJoin(...obs).subscribe(resArr => {
      for (let i = 0; i < resArr.length; i++) {
        const res = resArr[i];
        let str;
        if (res.type == 'success') {
          str = `${optType}成功`;
        } else {
          str = `${optType}失败`;
        }
        this.handoverCmp.message.create('success', str);
        this.getTcjhb(this.handoverCmp.tcjhb.repairid);
      }
    });
  }

  cleanUp(data) {
    if (data && data.length) {
      for (const item of data) {
        for (const list of Object.keys(item)) {
          switch (item[list]) {
            case 'null': case null: case 'undefined': case undefined:
            case 'false': case false: case 'NaN': case NaN: case 0:
              item[list] = '';
              break;
          }
        }
      }
    }
    return data;
  }
}
